import logging
import time
from datetime import datetime

from peewee import *
from api.utils import get_uuid
from api.db.db_models import DB, DataBaseModel


class rice_varieties(DataBaseModel):
    id = CharField(primary_key=True)  # 改为CharField以匹配varchar(36)
    seed_id = IntegerField(null=True)
    name = CharField(max_length=255, null=True)
    father_parent = CharField(max_length=255, null=True)
    mother_parent = CharField(max_length=255, null=True)
    parent_source = TextField(null=True)
    breeding_unit = TextField(null=True)
    variety_type = CharField(max_length=100, null=True)
    other_info = TextField(null=True)
    all_data = TextField(null=True)
    create_time = BigIntegerField()  # 添加所有时间字段
    create_date = CharField(max_length=32)
    update_time = BigIntegerField()
    update_date = CharField(max_length=32)

    class Meta:
        table_name = 'rice_varieties'
        indexes = (
            (('seed_id', 'name'), True),
        )

class rice_approvals(DataBaseModel):
    id = CharField(primary_key=True)  # 改为CharField以匹配varchar(36)
    variety_id = CharField()  # 改为CharField以匹配varchar(36)
    approval_number = CharField(max_length=100, null=True)
    applicant = TextField(null=True)
    breeder = TextField(null=True)
    origin = TextField(null=True)
    characteristics = TextField(null=True)
    yield_performance = TextField(null=True)
    cultivation_techniques = TextField(null=True)
    approval_opinion = TextField(null=True)
    all_data = TextField(null=True)
    other_info = TextField(null=True)
    create_time = BigIntegerField()  # 添加所有时间字段
    create_date = CharField(max_length=32)
    update_time = BigIntegerField()
    update_date = CharField(max_length=32)

    class Meta:
        table_name = 'rice_approvals'
        indexes = (
            (('variety_id', 'approval_number'), True),
        )

class RiceService:
    @classmethod
    def _get_current_timestamps(cls):
        """获取当前时间戳和日期字符串"""
        now = int(time.time())
        date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return now, date_str
    
    @classmethod
    @DB.connection_context()
    def _if_variety_id_exists(cls, variety_id):
        """检查品种ID是否已存在"""
        return rice_varieties.select().where(rice_varieties.seed_id == variety_id).exists()

    @classmethod
    @DB.connection_context()
    def save_variety_data(cls, seed_info, approval_data, variety_id):
        """保存品种数据"""
        try:
            # 获取当前时间
            now, date_str = cls._get_current_timestamps()

            # 保存品种基本信息
            variety_id_str = str(get_uuid())
            rice_varieties.create(
                id=variety_id_str,
                seed_id=variety_id,
                name=seed_info["种名"] if "种名" in seed_info else "",
                father_parent=seed_info.get("father_parent", ""),
                mother_parent=seed_info.get("mother_parent", ""),
                parent_source=seed_info["亲本来源"] if "亲本来源" in seed_info else "",
                breeding_unit=seed_info["选育单位"] if "选育单位" in seed_info else "",
                variety_type=seed_info["品种类型"] if "品种类型" in seed_info else "",
                all_data=seed_info["全信息"] if "全信息" in seed_info else "",
                other_info=seed_info["其他"] if "其他" in seed_info else "",
                create_time=now,
                create_date=date_str,
                update_time=now,
                update_date=date_str
            )

            # 保存审定信息
            for approval in approval_data:
                now, date_str = cls._get_current_timestamps()
                rice_approvals.create(
                    id=str(get_uuid()),
                    variety_id=variety_id_str,
                    approval_number=approval["审定编号"] if "审定编号" in approval else "",
                    applicant=approval["申请者"] if "申请者" in approval else "",
                    breeder=approval["育种者"] if "育种者" in approval else "",
                    origin=approval["品种来源"] if "品种来源" in approval else "",
                    characteristics=approval["特征特性"] if "特征特性" in approval else "",
                    yield_performance=approval["产量表现"] if "产量表现" in approval else "",
                    cultivation_techniques= approval["栽培技术要点"] if approval["栽培技术要点"] != "" else approval["栽培要点"],
                    approval_opinion=approval["审定意见"] if "审定意见" in approval else "",
                    all_data=approval["全信息"] if "全信息" in approval else "",
                    other_info=approval["其他"] if "其他" in approval else "",
                    create_time=now,
                    create_date=date_str,
                    update_time=now,
                    update_date=date_str
                )

            logging.info(f"成功保存品种ID: {variety_id}")
            return True

        except Exception as e:
            logging.error(f"保存数据失败: {e}")
            return False
        
    @classmethod
    @DB.connection_context()
    def get_varieties_list(cls, params):
        """获取水稻品种列表"""
        try:
            query = rice_varieties.select()

            # 精确匹配seed_id
            if 'seed_id' in params and params['seed_id'] != '':
                query = query.where(rice_varieties.seed_id == params['seed_id'])
            
            # 模糊匹配种名
            if 'name' in params and params['name']:
                query = query.where(rice_varieties.name.contains(params['name']))
            
            # 耐旱判断
            if params.get('drought_resistant', False):
                query = query.where(rice_varieties.variety_type.contains('旱'))
            
            # 糯性判断
            if params.get('glutinous', False):
                query = query.where(rice_varieties.variety_type.contains('糯'))
            
            # 形式判断
            form_type = params.get('form_type', '不限定')
            if form_type != '不限定':
                query = query.where(rice_varieties.variety_type.contains(form_type))
            
            # 水稻类型判断
            rice_type = params.get('rice_type', '不限定')
            type_mapping = {
                '常规稻': '常规',
                '杂交稻': '杂交',
                '三系杂交稻': '三系杂交',
                '两系杂交稻': '两系杂交',
                '不育系': '不育系'
            }
            if rice_type != '不限定' and rice_type in type_mapping:
                query = query.where(rice_varieties.variety_type.contains(type_mapping[rice_type]))
            
            # 分页处理
            page = params.get('page', 1)
            per_page = params.get('per_page', 20)
            paginated = query.paginate(page, per_page)
            total = query.count()
            
            # 转换为字典列表
            varieties = [{
                'id': variety.id,
                'seed_id': variety.seed_id,
                'name': variety.name,
                'mother_parent': variety.mother_parent,
                'variety_type': variety.variety_type,
                'breeding_unit': variety.breeding_unit,
                'create_time': variety.create_time
            } for variety in paginated]
            
            return {
                'items': varieties,
                'total': total,
                'page': page,
                'per_page': per_page
            }
        except Exception as e:
            logging.error(f"获取水稻品种列表失败: {e}")
            raise
        
    @classmethod
    @DB.connection_context()
    def get_variety_detail(cls, variety_id):
        """获取水稻品种详情"""
        try:
            # 查询品种基本信息
            variety = rice_varieties.get_or_none(rice_varieties.id == variety_id)
            if not variety:
                logging.warning(f"未找到品种ID: {variety_id}")
                return None
            
            # 查询审定信息
            approvals = rice_approvals.select().where(rice_approvals.variety_id == variety_id)
            
            # 转换为字典格式
            variety_data = {
                'id': variety.id,
                'seed_id': variety.seed_id,
                'name': variety.name,
                'father_parent': variety.father_parent,
                'mother_parent': variety.mother_parent,
                'parent_source': variety.parent_source,
                'breeding_unit': variety.breeding_unit,
                'variety_type': variety.variety_type,
                'other_info': variety.other_info,
                'all_data': variety.all_data,
                'approvals': [{
                    'approval_number': approval.approval_number,
                    'applicant': approval.applicant,
                    'breeder': approval.breeder,
                    'origin': approval.origin,
                    'characteristics': approval.characteristics,
                    'yield_performance': approval.yield_performance,
                    'cultivation_techniques': approval.cultivation_techniques,
                    'approval_opinion': approval.approval_opinion,
                    'other_info': approval.other_info,
                    'all_data': approval.all_data,
                } for approval in approvals]
            }
            
            return variety_data
        except Exception as e:
            logging.error(f"获取水稻品种详情失败: {e}")
            raise
